#include "shebei.h"
#include "set.h"
#include "widget.h"
#include "history.h"
#include "ui_shebei.h"

shebei::shebei(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::shebei)
{
    ui->setupUi(this);

    // 连接槽函数
    connect(ui->Push_Door,SIGNAL(clicked()),this,SLOT(Push_Door_Slot()));
    connect(ui->Push_Fan,SIGNAL(clicked()),this,SLOT(Push_Fan_Slot()));
    connect(ui->push_Rev,SIGNAL(clicked()),this,SLOT(Push_Rev_Slot()));
    connect(ui->push_Temp,SIGNAL(clicked()),this,SLOT(Push_Temp_Slot()));
    connect(ui->Push_Ekey,SIGNAL(clicked()),this,SLOT(Push_Ekey_Slot()));
    connect(ui->push_shuaxin,SIGNAL(clicked()),this,SLOT(Push_Shuaxin_Slot()));
    connect(ui->push_fdj,SIGNAL(clicked()),this,SLOT(Push_fdj_Slot()));
    connect(this,SIGNAL(shiyanshi_signal(int)),this,SLOT(shiyanshi_Slot(int)));



}

shebei::~shebei()
{
    delete ui;

}


// 开关门
void shebei::Push_Door_Slot()
{
    // 创建JSON对象
    QJsonObject stm32Object;
    QJsonObject modbusObject;

    stm32Object["key"] = 102;
    stm32Object["type"] = 2;

    modbusObject["key"] = 204;
    modbusObject["type"] = 2;
    modbusObject["addr"] = 40000;

    // 判断当前状态，并且点击完毕之后修改状态
    if(ui->Push_Door->text() == QString("门已开"))
    {
        stm32Object["val"] = 0;
        modbusObject["val"] = 0;
        ui->Push_Door->setText(QString("门已关"));
        qDebug() << "门已关" ;
    }
    else if(ui->Push_Door->text() == QString("门已关"))
    {
        stm32Object["val"] = 1;
        modbusObject["val"] = 1;
        ui->Push_Door->setText(QString("门已开"));
        qDebug() << "门已开" ;
    }

    QJsonObject stm32rootObject;
    stm32rootObject["stm32"] = stm32Object;

    QJsonObject modrootObject;
    modrootObject["modbus"] = modbusObject;


    // 将JSON对象序列化为文档
    QJsonDocument stm32jsonDoc(stm32rootObject);
    QJsonDocument modjsonDoc(modrootObject);

    // 将文档转换为字符串（QByteArray）
    QByteArray stm32jsonString = stm32jsonDoc.toJson(QJsonDocument::Compact);
    QByteArray modjsonString = modjsonDoc.toJson(QJsonDocument::Compact);

    qDebug() << stm32jsonString ;
    qDebug() << modjsonString ;

    if(ui->Push_Door->text() == QString("门已关") && ui->push_fdj->text() == QString("运行中"))
    {
        qDebug() << "舱门已关，发动机已运行，实验室正在实验";
        emit shiyanshi_signal(1);
    }
    else
    {
        emit shiyanshi_signal(0);
    }


    // mqtt发布控制数据
    QMQTT::Message message;
    message.setTopic(GlobalVal::topic);

    for(int i = 0; i < 2;i++)
    {
        if(i == 0)
        {
            message.setPayload(stm32jsonString);
            quint16 result = GlobalVal::mqtt->publish(message);
            qDebug() << "修改stm32的门" ;
            if (result == 0)
            {
                qDebug() << "Message published successfully.";
            }
            else
            {
                 qDebug() << "Failed to publish message. Error code:" << result;
            }
        }
        else if(i == 1)
        {
            message.setPayload(modjsonString);
            quint16 result = GlobalVal::mqtt->publish(message);
            qDebug() << "修改modbus的门" ;
            if (result == 0)
            {
                qDebug() << "Message published successfully.";
            }
            else
            {
                 qDebug() << "Failed to publish message. Error code:" << result;
            }
        }

    }


}

// 风扇开关
void shebei::Push_Fan_Slot()
{
    // 创建JSON对象
        QJsonObject stm32Object;
        stm32Object["key"] = 105;
        stm32Object["type"] = 2;
        // 判断当前状态，点击完毕之后修改状态与按钮中的文字
        if(ui->Push_Fan->text() == QString("运行中"))
        {
            stm32Object["val"] = 0;
            ui->Push_Fan->setText(QString("停止"));
            qDebug() << "风扇停止运行" ;
        }
        else if(ui->Push_Fan->text() == QString("停止"))
        {
            stm32Object["val"] = 1;
            ui->Push_Fan->setText(QString("运行中"));
            qDebug() << "风扇运行" ;
        }

        QJsonObject rootObject;
        rootObject["stm32"] = stm32Object;

        // 将JSON对象序列化为文档
        QJsonDocument jsonDoc(rootObject);
        // 将文档转换为字符串（QByteArray）
        QByteArray jsonString = jsonDoc.toJson(QJsonDocument::Compact);

        qDebug() << jsonString ;

        // mqtt发布控制数据
        QMQTT::Message message;
        message.setTopic(GlobalVal::topic);
        qDebug() << GlobalVal::topic;
        message.setPayload(jsonString);
        quint16 result = GlobalVal::mqtt->publish(message);
        if (result == 0)
        {
            qDebug() << "Message published successfully.";
        }
        else
        {
             qDebug() << "Failed to publish message. Error code:" << result;
        }

}

// 设置转速
void shebei::Push_Rev_Slot()
{
    // 创建JSON对象
    QJsonObject modbusObject;
    modbusObject["key"] = 202;
    modbusObject["type"] = 2;
    modbusObject["addr"] = 30001;
    modbusObject["val"] = ui->Revolution_Set->text().toInt();

    QJsonObject rootObject;
    rootObject["modbus"] = modbusObject;

    // 将JSON对象序列化为文档
    QJsonDocument jsonDoc(rootObject);
    // 将文档转换为字符串（QByteArray）
    QByteArray jsonString = jsonDoc.toJson(QJsonDocument::Compact);

    qDebug() << "设置转速为：" << ui->Revolution_Set->text().toInt();
    qDebug() << jsonString ;

    // mqtt发布控制数据
    QMQTT::Message message;
    message.setTopic(GlobalVal::topic);
    qDebug() << GlobalVal::topic;
    message.setPayload(jsonString);
    quint16 result = GlobalVal::mqtt->publish(message);
    if (result == 0)
    {
        qDebug() << "Message published successfully.";
    }
    else
    {
         qDebug() << "Failed to publish message. Error code:" << result;
    }
}

// 设置实验室温度
void shebei::Push_Temp_Slot()
{
    // 创建JSON对象
    QJsonObject stm32Object;
    stm32Object["key"] = 101;
    stm32Object["type"] = 3;
    stm32Object["val"] = ui->Temp_Set->text().toDouble();

    QJsonObject rootObject;
    rootObject["stm32"] = stm32Object;

    // 将JSON对象序列化为文档
    QJsonDocument jsonDoc(rootObject);
    // 将文档转换为字符串（QByteArray）
    QByteArray jsonString = jsonDoc.toJson(QJsonDocument::Compact);

    qDebug() << "设置温度为：" << ui->Temp_Set->text().toDouble();
    qDebug() << jsonString ;

    // mqtt发布控制数据
    QMQTT::Message message;
    message.setTopic(GlobalVal::topic);
    qDebug() << GlobalVal::topic;
    message.setPayload(jsonString);
    quint16 result = GlobalVal::mqtt->publish(message);
    if (result == 0)
    {
        qDebug() << "Message published successfully.";
    }
    else
    {
         qDebug() << "Failed to publish message. Error code:" << result;
    }
}

// 发动机急停
void shebei::Push_Ekey_Slot()
{
    // 创建JSON对象
    QJsonObject stm32Object;
    stm32Object["key"] = 106;
    stm32Object["type"] = 2;
    stm32Object["val"] = 0;

    QJsonObject rootObject;
    rootObject["stm32"] = stm32Object;

    // 将JSON对象序列化为文档
    QJsonDocument jsonDoc(rootObject);
    // 将文档转换为字符串（QByteArray）
    QByteArray jsonString = jsonDoc.toJson(QJsonDocument::Compact);

    ui->push_fdj->setText(QString("停止"));
    qDebug() << "发动机急停" ;
    qDebug() << jsonString ;

    emit shiyanshi_signal(0);

    // mqtt发布控制数据
    QMQTT::Message message;
    message.setTopic(GlobalVal::topic);
    qDebug() << GlobalVal::topic;
    message.setPayload(jsonString);
    quint16 result = GlobalVal::mqtt->publish(message);
    if (result == 0)
    {
        qDebug() << "Message published successfully.";
    }
    else
    {
         qDebug() << "Failed to publish message. Error code:" << result;
    }

}

// 刷新数据
void shebei::Push_Shuaxin_Slot()
{
    // 创建根对象
    QJsonObject rootObject;

    // 添加版本信息
    rootObject["version"] = "v1.0";

    // 创建报告对象
    QJsonObject reportObject;
    reportObject["type"] = 0;
    reportObject["period"] = 5;

    // 将报告对象添加到根对象
    rootObject["report"] = reportObject;

    // 创建JSON文档
    QJsonDocument jsonDoc(rootObject);

    // 将JSON文档转换为字符串
    QByteArray jsonString = jsonDoc.toJson(QJsonDocument::Compact);

    // 打印JSON字符串
    qDebug() << jsonString;
    qDebug() << "刷新数据";

    // mqtt发布控制数据
    QMQTT::Message message;
    message.setTopic(GlobalVal::topic);
    qDebug() << GlobalVal::topic;
    message.setPayload(jsonString);
    quint16 result = GlobalVal::mqtt->publish(message);
    if (result == 0)
    {
        qDebug() << "Message published successfully.";
    }
    else
    {
         qDebug() << "Failed to publish message. Error code:" << result;
    }

}

// 发动机启动与停止
void shebei::Push_fdj_Slot()
{
    // 创建JSON对象
    QJsonObject stm32Object;
    stm32Object["key"] = 104;
    stm32Object["type"] = 2;

    // 判断当前状态，点击完毕之后修改状态与按钮中的文字
    if(ui->push_fdj->text() == QString("运行中"))
    {
        stm32Object["val"] = 0;
        ui->push_fdj->setText(QString("停止"));
        qDebug() << "发动机停止运行" ;
    }
    else if(ui->push_fdj->text() == QString("停止"))
    {
        stm32Object["val"] = 1;
        ui->push_fdj->setText(QString("运行中"));
        qDebug() << "发动机开始运行" ;
    }

    QJsonObject rootObject;
    rootObject["stm32"] = stm32Object;

    // 将JSON对象序列化为文档
    QJsonDocument jsonDoc(rootObject);
    // 将文档转换为字符串（QByteArray）
    QByteArray jsonString = jsonDoc.toJson(QJsonDocument::Compact);

    if(ui->Push_Door->text() == QString("门已关") && ui->push_fdj->text() == QString("运行中"))
    {
        qDebug() << "舱门已关，发动机已运行，实验室正在实验";
        emit shiyanshi_signal(1);
    }
    else
    {
        emit shiyanshi_signal(0);
    }

    qDebug() << jsonString ;

    // mqtt发布控制数据
    QMQTT::Message message;
    message.setTopic(GlobalVal::topic);
    qDebug() << GlobalVal::topic;
    message.setPayload(jsonString);
    quint16 result = GlobalVal::mqtt->publish(message);
    if (result == 0)
    {
        qDebug() << "Message published successfully.";
    }
    else
    {
         qDebug() << "Failed to publish message. Error code:" << result;
    }
}

// 实验室工作状态，自定义信号与槽函数
void shebei::shiyanshi_Slot(int shi)
{
    if(shi == 1)
    {
        ui->Led1_Text->setText("测试中");
    }
    else
    {
        ui->Led1_Text->setText("无测试");
    }

}


// 将接收到的信息显示到界面中
void shebei::dataup(QByteArray mqttarray)
{
    qDebug() << "存在" ;
    QJsonParseError jsonError;
    QJsonDocument doucment = QJsonDocument::fromJson(mqttarray, &jsonError);  // 转化为 JSON 文档
    QJsonObject object = doucment.object();  // 获取根对象


    // 通过判断是否存在report节点来判断是否为变化上报
    if(object.contains("report"))
    {
        qDebug() << "存在report节点" ;
        // 获取 "stm32" 对象
        QJsonObject stm32Object = object.value("stm32").toObject();

        // 获取 "data" 数组
        QJsonArray dataArray = stm32Object.value("data").toArray();

        // 循环读取data节点数组中的数据
        for (int i = 0;i < dataArray.size(); i++)
        {
            QJsonObject itemObject = dataArray[i].toObject();
            int key = itemObject.value("key").toInt();
            switch (key)
            {
            case 101:
            {
                // 温度数据
                float newval = itemObject.value("newval").toDouble();
                QString str1 = QString::number(newval);
//                QString str2 = "℃";
//                QString str = str1 + str2;
                // 向文本框中写温度
                ui->Temp_Text->setText(str1);
                qDebug() << "温度:" << str1;
                break;
            }
            case 102:
            {
                // 门的状态
                bool newval = itemObject.value("newval").toBool();
                if(newval == 1)
                {
                    // 向文本框内写入 开
                    ui->Push_Door->setText("门已开");
                    qDebug() << "门:" << "门已开";
                }
                else
                {
                    // 向文本框内写入 关
                    ui->Push_Door->setText("门已关");
                    qDebug() << "门:" << "门已关";
                }

                break;
            }
            case 103:
            {
                // 实验室的工作状态
                bool newval = itemObject.value("newval").toBool();
                if(newval == 1)
                {
                    // 向文本框内写入开
                    ui->Led1_Text->setText("测试中");
                    qDebug() << "实验室:" << "测试中";
                }
                else
                {
                    // 向文本框内写入 关
                    ui->Led1_Text->setText("无测试");
                    qDebug() << "实验室:" << "无测试";
                }

                break;
            }
            case 104:
            {
                // 发动机的工作状态
                bool newval = itemObject.value("newval").toBool();
                if(newval == 1)
                {
                    // 向文本框内写入 运行中
                    ui->push_fdj->setText("运行中");
                    qDebug() << "发动机:" << "运行中";
                }
                else
                {
                    // 向文本框内写入 停止
                    ui->push_fdj->setText("停止");
                    qDebug() << "发动机:" << "停止";
                }

                break;
            }
            case 105:
            {
                // 风扇的工作状态
                bool newval = itemObject.value("newval").toBool();
                if(newval == 1)
                {
                    // 向文本框内写入 运行中
                    ui->Push_Fan->setText("运行中");
                }
                else
                {
                    // 向文本框内写入 停止
                    ui->Push_Fan->setText("停止");
                }

                break;
            }
            default:
                break;
            }

        }

        // 获取 "modbus" 对象
        QJsonObject modbusObject = object.value("modbus").toObject();

        // 获取 "data" 数组
        dataArray = modbusObject.value("data").toArray();
        // 循环读取data节点数组中的数据
        for (int i = 0;i < dataArray.size(); i++)
        {
            QJsonObject itemObject = dataArray[i].toObject();
            int key = itemObject.value("key").toInt();

            switch (key)
            {
            case 201:
            {
                // 发动机温度数据
                float newval = itemObject.value("newval").toDouble();
                QString str1 = QString::number(newval);
//                QString str2 = "℃";
//                QString str = str1 + str2;
                // 向文本框中写温度
                ui->Etemp_Text->setText(str1);

                qDebug() << "发动机温度:" << str1;

                break;
            }
            case 203:
            {
                // 二氧化碳浓度
                float value = itemObject.value("newval").toDouble();
                // float newval = itemObject.value("newval").toDouble();
                QString str1 = QString::number(value);
//                QString str2 = "%";
//                QString str = str1 + str2;
                // 向文本框中写浓度
                ui->Carbon_Text->setText(str1);

                qDebug() << "二氧化碳浓度:" << str1;

                break;
            }
            case 202:
            {
                // 转速
                float newval = itemObject.value("newval").toDouble();
                QString str1 = QString::number(newval);
//                QString str2 = "转";
//                QString str = str1 + str2;
                // 向文本框中写入转速
                ui->Revolution_Text->setText(str1);
                break;
            }
            default:
                break;
            }
        }
    }
    else
    {
        qDebug() << "没有report节点，为变化上报" ;
        int key = object.value("key").toInt();

        switch (key)
        {
        case 101:
        {
            float newvalue = object.value("newval").toDouble();
            QString str1 = QString::number(newvalue);
            QString str2 = "℃";
            QString str = str1 + str2;
            // 向文本框中写温度
            ui->Temp_Text->setText(str);
            qDebug() << "温度改变:" << str;
            break;
        }
        case 102:
        {
            // 门的状态
            bool newvalue = object.value("newval").toBool();
            if(newvalue == 1)
            {
                // 向文本框内写入 开
                ui->Push_Door->setText("门已开");
                qDebug() << "门状态改变:" << "门已开";
            }
            else
            {
                // 向文本框内写入 关
                ui->Push_Door->setText("门已关");
                qDebug() << "门状态改变:" << "门已关";
            }

            break;
        }
        case 103:
        {
            // 实验室的工作状态
            bool newvalue = object.value("newval").toBool();
            if(newvalue == 1)
            {
                // 向文本框内写入开
                ui->Led1_Text->setText("测试中");
                qDebug() << "实验室改变:" << "测试中";
            }
            else
            {
                // 向文本框内写入 关
                ui->Led1_Text->setText("无测试");
                qDebug() << "实验室改变:" << "无测试";
            }

            break;
        }
        case 104:
        {
            // 发动机的工作状态
            bool newvalue = object.value("newval").toBool();
            if(newvalue == 1)
            {
                // 向文本框内写入 运行中
                ui->push_fdj->setText("运行中");
                qDebug() << "发动机状态改变:" << "运行中";
            }
            else
            {
                // 向文本框内写入 停止
                ui->push_fdj->setText("停止");
                qDebug() << "发动机状态改变:" << "停止";
            }

            break;
        }
        case 105:
        {
            // 风扇的工作状态
            bool newvalue = object.value("newval").toBool();
            if(newvalue == 1)
            {
                // 向文本框内写入 运行中
                ui->Push_Fan->setText("运行中");
                qDebug() << "风扇改变:" << "运行中";
            }
            else
            {
                // 向文本框内写入 停止
                ui->Push_Fan->setText("停止");
                qDebug() << "风扇改变:" << "停止";
            }

            break;
        }
        case 201:
        {
            // 发动机温度数据
            float newvalue = object.value("newval").toDouble();
            QString str1 = QString::number(newvalue);
            QString str2 = "℃";
            QString str = str1 + str2;
            // 向文本框中写温度
            ui->Etemp_Text->setText(str);

            qDebug() << "发动机温度改变:" << str;

            break;
        }
        case 202:
        {
            // 二氧化碳浓度
            float newvalue = object.value("newval").toDouble();
            QString str1 = QString::number(newvalue);
            QString str2 = "%";
            QString str = str1 + str2;
            // 向文本框中写浓度
            ui->Carbon_Text->setText(str);

            qDebug() << "二氧化碳浓度改变:" << str;

            break;
        }
        case 203:
        {
            // 转速
            float newvalue = object.value("newval").toDouble();
            QString str1 = QString::number(newvalue);
            QString str2 = "转";
            QString str = str1 + str2;
            // 向文本框中写入转速
            ui->Revolution_Text->setText(str);
            qDebug() << "转速改变:" << str;

            break;
        }
        default:
            break;
        }

    }


}
